﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;
using SixLabors.ImageSharp;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using Furion;
using Serilog;
using Furion.RemoteRequest.Extensions;
using HttpMethod = System.Net.Http.HttpMethod;

namespace Admin.NET.Application
{
    /// <summary>
    /// 领料单服务
    /// </summary>
    [ApiDescriptionSettings("单据管理", Name = "WmsTakeMaterialOrder", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsTakeMaterialOrderService : IWmsTakeMaterialOrderService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsTakeMaterialOrder,MasterDbContextLocator> _wmsTakeMaterialOrderRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();
        private readonly IRepository<WmsTakeMaterialOrderDetail, MasterDbContextLocator> _wmsTakeMaterialOrderDetailRep;
        private readonly IRepository<WmsOrderType, MasterDbContextLocator> _wmsOrderTypeRep;
        private readonly IRepository<WmsPlace, MasterDbContextLocator> _wmsPlaceRep;
        private readonly IRepository<WmsMaterialStock, MasterDbContextLocator> _wmsMaterialStockRep;
        private readonly IRepository<WmsMaterialContainer, MasterDbContextLocator> _wmsMaterialContainerRep;
        private readonly IRepository<WmsSortOrder, MasterDbContextLocator> _wmsSortOrderRep;
        private readonly IRepository<WmsTask, MasterDbContextLocator> _wmsTaskRep;

        public WmsTakeMaterialOrderService(
            IRepository<WmsTakeMaterialOrder,MasterDbContextLocator> wmsTakeMaterialOrderRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
            ,IRepository<WmsTakeMaterialOrderDetail, MasterDbContextLocator> wmsTakeMaterialOrderDetailRep
            , IRepository<WmsOrderType, MasterDbContextLocator> wmsOrderTypeRep
            , IRepository<WmsPlace, MasterDbContextLocator> wmsPlaceRep
            , IRepository<WmsMaterialStock, MasterDbContextLocator> wmsMaterialStockRep
            , IRepository<WmsMaterialContainer, MasterDbContextLocator> wmsMaterialContainerRep
            , IRepository<WmsSortOrder, MasterDbContextLocator> wmsSortOrderRep
            , IRepository<WmsTask, MasterDbContextLocator> wmsTaskRep
        )
        {
            _wmsTakeMaterialOrderRep = wmsTakeMaterialOrderRep;
         _sysDictTypeRep = sysDictTypeRep;
         _sysDictDataRep = sysDictDataRep;
         _sysExcelTemplateService = sysExcelTemplateService;
            _wmsTakeMaterialOrderDetailRep = wmsTakeMaterialOrderDetailRep;
            _wmsOrderTypeRep = wmsOrderTypeRep;
            _wmsPlaceRep = wmsPlaceRep;
            _wmsMaterialStockRep = wmsMaterialStockRep;
            _wmsMaterialContainerRep = wmsMaterialContainerRep;
            _wmsSortOrderRep =  wmsSortOrderRep;
            _wmsTaskRep = wmsTaskRep;
        }

        /// <summary>
        /// 分页查询领料单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsTakeMaterialOrderOutput>> Page([FromQuery] WmsTakeMaterialOrderSearch input)
        {
            var wmsTakeMaterialOrders = await _wmsTakeMaterialOrderRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.MoveType), u => EF.Functions.Like(u.MoveType, $"%{input.MoveType.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.NO), u => EF.Functions.Like(u.NO, $"%{input.NO.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.WBSElementcode), u => EF.Functions.Like(u.WBSElementcode, $"%{input.WBSElementcode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.BenefitingDepartcode), u => EF.Functions.Like(u.BenefitingDepartcode, $"%{input.BenefitingDepartcode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.CostCenterID), u => EF.Functions.Like(u.CostCenterID, $"%{input.CostCenterID.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.FI_Client_Analysis_H), u => EF.Functions.Like(u.FI_Client_Analysis_H, $"%{input.FI_Client_Analysis_H.Trim()}%"))
                                     .Where(input.IsInnerCompany != null, u => u.IsInnerCompany == input.IsInnerCompany)
                                     .Where(!string.IsNullOrEmpty(input.PickerID), u => EF.Functions.Like(u.PickerID, $"%{input.PickerID.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.WarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{input.WarehouseCentername.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Companyname), u => EF.Functions.Like(u.Companyname, $"%{input.Companyname.Trim()}%"))
                                     .Where(input.OrderStatus != null, u => u.OrderStatus == input.OrderStatus)
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsTakeMaterialOrderSearch>(input))
                                     .ProjectToType<WmsTakeMaterialOrderOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsTakeMaterialOrders;
        }

        /// <summary>
        /// 不分页查询领料单列表
        /// </summary>
        /// <param name="input">领料单查询参数</param>
        /// <returns>(领料单)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsTakeMaterialOrderOutput>> ListNonPageAsync([FromQuery] WmsTakeMaterialOrderSearchNonPage input)
        {
            var pMoveType = input.MoveType?.Trim() ?? "";
            var pNO = input.NO?.Trim() ?? "";
            var pWBSElementcode = input.WBSElementcode?.Trim() ?? "";
            var pBenefitingDepartcode = input.BenefitingDepartcode?.Trim() ?? "";
            var pCostCenterID = input.CostCenterID?.Trim() ?? "";
            var pFI_Client_Analysis_H = input.FI_Client_Analysis_H?.Trim() ?? "";
            var pIsInnerCompany = input.IsInnerCompany;
            var pPickerID = input.PickerID?.Trim() ?? "";
            var pWarehouseCentername = input.WarehouseCentername?.Trim() ?? "";
            var pCompanyname = input.Companyname?.Trim() ?? "";
            var pOrderStatus = input.OrderStatus;
            var wmsTakeMaterialOrders = await _wmsTakeMaterialOrderRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pMoveType), u => EF.Functions.Like(u.MoveType, $"%{pMoveType}%")) 
                .Where(!string.IsNullOrEmpty(pNO), u => EF.Functions.Like(u.NO, $"%{pNO}%")) 
                .Where(!string.IsNullOrEmpty(pWBSElementcode), u => EF.Functions.Like(u.WBSElementcode, $"%{pWBSElementcode}%")) 
                .Where(!string.IsNullOrEmpty(pBenefitingDepartcode), u => EF.Functions.Like(u.BenefitingDepartcode, $"%{pBenefitingDepartcode}%")) 
                .Where(!string.IsNullOrEmpty(pCostCenterID), u => EF.Functions.Like(u.CostCenterID, $"%{pCostCenterID}%")) 
                .Where(!string.IsNullOrEmpty(pFI_Client_Analysis_H), u => EF.Functions.Like(u.FI_Client_Analysis_H, $"%{pFI_Client_Analysis_H}%")) 
                .Where(pIsInnerCompany != null, u => u.IsInnerCompany == pIsInnerCompany)
                .Where(!string.IsNullOrEmpty(pPickerID), u => EF.Functions.Like(u.PickerID, $"%{pPickerID}%")) 
                .Where(!string.IsNullOrEmpty(pWarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{pWarehouseCentername}%")) 
                .Where(!string.IsNullOrEmpty(pCompanyname), u => EF.Functions.Like(u.Companyname, $"%{pCompanyname}%")) 
                .Where(pOrderStatus != null, u => u.OrderStatus == pOrderStatus)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsTakeMaterialOrderOutput>()
            .ToListAsync();
            return wmsTakeMaterialOrders;
        }

        /// <summary>
        /// 获取单据明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("PageDetail")]
        public async Task<PageResult<WmsTakeMaterialOrderDetailOutput>> PageDetail([FromQuery] TakePageDetailInput input)
        {
            var wmsOrders = await _wmsTakeMaterialOrderDetailRep.DetachedEntities
                                     .Where(input.Id != null, u => u.OrderId == input.Id)
                                     .ProjectToType<WmsTakeMaterialOrderDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// 分页查询物料库存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("stockPage")]
        public async Task<PageResult<TakeMaterialStockOutput>> StockPage([FromQuery] TakeMaterialStockSearch input)
        {
            //从未执行和执行中的任务中获取库位进行筛选(未写)

            //查询所有被锁定库位和待出的库存
            var lockPlace = await _wmsPlaceRep.DetachedEntities.Where(x => x.Islock == YesOrNot.Y || x.PlaceStatus == PlaceStatus.DAICHU).Select(x => x.PlaceCode).ToListAsync();

            var wmsMaterialStocks = await _wmsMaterialStockRep.DetachedEntities
                .Where(u => u.StockNumber != 0)
                .Where(!string.IsNullOrEmpty(input.MaterialNo), u => EF.Functions.Like(u.MaterialNo, $"%{input.MaterialNo.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.MaterialName), u => EF.Functions.Like(u.MaterialName, $"%{input.MaterialName.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.ProjectCode), u => EF.Functions.Like(u.ProjectCode, $"%{input.ProjectCode.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.ContractCode), u => EF.Functions.Like(u.ContractCode, $"%{input.ContractCode.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.TACode), u => EF.Functions.Like(u.TACode, $"%{input.TACode.Trim()}%"))
                .Where(input.SearchBeginTime != null && input.SearchEndTime != null, u => u.CreatedTime >= DateTime.Parse(input.SearchBeginTime.Trim()) &&
                                                                   u.CreatedTime <= DateTime.Parse(input.SearchEndTime.Trim()))
                .Where(u => u.AreaId == 472817877401669)
                .Where(u => !lockPlace.Contains(u.PlaceCode))
                .ProjectToType<TakeMaterialStockOutput>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsMaterialStocks;
        }

        /// <summary>
        /// 物料编码下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetMaterialNoList")]
        public async Task<List<MaterialNoListOutput>> GetMaterialNoList()
        {
            // 查询库位表状态为存货的库位作为查询库存的条件 固定库区
            List<string> wmsPlaceCodes = await _wmsPlaceRep.Where(u => u.PlaceStatus == PlaceStatus.CUNHUO && u.AreaId == 472817877401669)
                .Select(t => t.PlaceCode).ToListAsync();
            //从未执行和执行中的任务中获取库位进行筛选(未写)
            //查询所有被锁定库位和待出的库存
            var lockPlace = await _wmsPlaceRep.DetachedEntities.Where(x => x.Islock == YesOrNot.Y || x.PlaceStatus == PlaceStatus.DAICHU).Select(x => x.PlaceCode).ToListAsync();
            //查询库存
            var wmsMaterialStocks = await _wmsMaterialStockRep.DetachedEntities
                .ToListAsync();
            //未执行或执行中的明细托盘相关库存不继续显示
            wmsMaterialStocks = wmsMaterialStocks
                .Where(u => !lockPlace.Contains(u.PlaceCode))
                .GroupBy(x => x.MaterialNo).Select(x => x.First()).ToList();
            List<MaterialNoListOutput> MaterialNoListOutputLists = new List<MaterialNoListOutput>();
            foreach (var item in wmsMaterialStocks)
            {
                MaterialNoListOutput MaterialNoListOutput = new MaterialNoListOutput();
                MaterialNoListOutput.Code = item.MaterialNo;
                MaterialNoListOutput.MaterialNo = item.MaterialNo;
                MaterialNoListOutputLists.Add(MaterialNoListOutput);
            }
            return MaterialNoListOutputLists;
        }

        /// <summary>
        /// 项目编码下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetProjectCodeList")]
        public async Task<List<ProjectCodeListOutput>> GetProjectCodeList()
        {
            // 查询库位表状态为存货的库位作为查询库存的条件 固定库区
            List<string> wmsPlaceCodes = await _wmsPlaceRep.Where(u => u.PlaceStatus == PlaceStatus.CUNHUO && u.AreaId == 472817877401669)
                .Select(t => t.PlaceCode).ToListAsync();
            //从未执行和执行中的任务中获取库位进行筛选(未写)
            //查询所有被锁定库位和待出的库存
            var lockPlace = await _wmsPlaceRep.DetachedEntities.Where(x => x.Islock == YesOrNot.Y || x.PlaceStatus == PlaceStatus.DAICHU).Select(x => x.PlaceCode).ToListAsync();
            //查询库存
            var wmsMaterialStocks = await _wmsMaterialStockRep.DetachedEntities
                .ToListAsync();
            //未执行或执行中的明细托盘相关库存不继续显示
            wmsMaterialStocks = wmsMaterialStocks
                .Where(u => !lockPlace.Contains(u.PlaceCode))
                .GroupBy(x => x.ProjectCode).Select(x => x.First()).ToList();
            List<ProjectCodeListOutput> ProjectCodeListOutputLists = new List<ProjectCodeListOutput>();
            foreach (var item in wmsMaterialStocks)
            {
                ProjectCodeListOutput ProjectCodeListOutput = new ProjectCodeListOutput();
                ProjectCodeListOutput.Code = item.ProjectCode;
                ProjectCodeListOutput.ProjectCode = item.ProjectCode;
                ProjectCodeListOutputLists.Add(ProjectCodeListOutput);
            }
            return ProjectCodeListOutputLists;
        }

        /// <summary>
        /// 增加领料单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWmsTakeMaterialOrderInput input)
        {
            // 查询单据小类是“生产入库”的Id
            var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("领料出库"));
            var wmsTakeMaterialOrder = input.Adapt<WmsTakeMaterialOrder>();
            wmsTakeMaterialOrder.SOID = 66666;
            wmsTakeMaterialOrder.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
            wmsTakeMaterialOrder.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
            wmsTakeMaterialOrder.OrderStatus = OrderStatusEnum.WEIXIAFA;
            await _wmsTakeMaterialOrderRep.InsertAsync(wmsTakeMaterialOrder);
        }

        /// <summary>
        /// 增加领料单(yigo系统获取)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("TakeOrderAdd")]
        [UnitOfWork]
        public async Task TakeOrderAdd()
        {
            //获取领料申请单
            string url = App.Configuration["YiGoWebApi:QueryOutBoundNotice"];
            var Billdate_S = DateTime.Now.AddDays(-15).ToString("yyyy-MM-dd");
            var Billdate_E = DateTime.Now.AddDays(15).ToString("yyyy-MM-dd");
            //写日志文件
            //Log.Error($"[TransferContainerCode][ContainerCode:{input.ContainerCode}][url:{url}]");
            var response = await url.SetHttpMethod(System.Net.Http.HttpMethod.Post)
                                    .SetBody(new Dictionary<string, object> {
                                            { "Billdate_S", Billdate_S },
                                            { "Billdate_E", Billdate_E},
                                    }, "application/json").PostAsStringAsync();
            var Data = response.FromJson<WmsTakeMaterialOrderOutputByYiGO>();
            var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("领料出库"));
            foreach (var item in Data.Data)
            {
                item.Id = Yitter.IdGenerator.YitIdHelper.NextId();
                var wmsTakeMaterialOrder = item.Adapt<WmsTakeMaterialOrder>();
                var isExcit = await _wmsTakeMaterialOrderRep.AnyAsync(x => x.NO == item.NO);
                if (!isExcit)
                {
                    wmsTakeMaterialOrder.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
                    wmsTakeMaterialOrder.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
                    await _wmsTakeMaterialOrderRep.InsertNowAsync(wmsTakeMaterialOrder);
                    foreach (var item1 in item.Dtls)
                    {
                        var wmsTakeMaterialDeatail = item1.Adapt<WmsTakeMaterialOrderDetail>();
                        wmsTakeMaterialDeatail.OrderId = item.Id;
                        await _wmsTakeMaterialOrderDetailRep.InsertNowAsync(wmsTakeMaterialDeatail);
                    }
                }    
            }
        }
        /// <summary>
        /// 领料下架接口(yigo系统)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("ReturnTakeOrder")]
        [UnifyResult(typeof(object))]
        [UnitOfWork]
        public async Task<object> ReturnTakeOrder([FromBody] ReturnTakeOrderInput input)
        {
            try
            {
                //创建指定名称的订单操作
                string url = App.Configuration["YiGoWebApi:CreateTX211"];
                //获取主单据
                var wmsTakeMaterialOrderModal = await _wmsTakeMaterialOrderRep.FirstOrDefaultAsync(x => x.Id == input.Id);
                if (wmsTakeMaterialOrderModal == null) throw Oops.Oh("单据信息不存在!");
                // 写日志文件
                Log.Error($"[领料下架][单据号:{wmsTakeMaterialOrderModal.NO}][url:{url}]");

                var response = await url.SetHttpMethod(HttpMethod.Post)
                                        .SetBody(input, "application/json")
                                        .PostAsAsync<ReturnTakeOrderOutput>();
                // 写日志文件
                Log.Error($"[领料下架][单据号:{wmsTakeMaterialOrderModal.NO}][response:{response.ToJson()}]");

                return XnRestfulResultProvider.RESTfulResult(response);
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex.Message);
            }
        }


        /// <summary>
        /// 下发领料单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("DistributeOrder")]
        [UnitOfWork]
        public async Task DistributeOrder(DistributeOrderInput input)
        {
            // 查询单据小类是“生产入库”的Id
            var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("领料出库"));
            //获取领料单据
            var wmsTakeMaterialOrder = await _wmsTakeMaterialOrderRep
                .Where(x=>x.Id == input.Id && x.OrderLargeCategory == wmsOrderType.Pid && x.OrderSubclass == wmsOrderType.Id)
                .ProjectToType<WmsTakeMaterialOrder>()
                .FirstOrDefaultAsync();
            if (wmsTakeMaterialOrder == null) throw Oops.Oh("单据不存在!");
            wmsTakeMaterialOrder.OrderStatus = OrderStatusEnum.YIXIAFA;
            //更改单据状态为已下发
            await _wmsTakeMaterialOrderRep.UpdateAsync(wmsTakeMaterialOrder);
            //根据领料单明细生成分拣单
            foreach (var item in wmsTakeMaterialOrder.WmsTakeMaterialOrderDetail)
            {
                //获取所有为该明细物料编码的库存(不为完成状态的出库任务的库位要排除，待开发)
                var wmsMaterialStocks = await _wmsMaterialStockRep.DetachedEntities.Where(x => x.MaterialNo == item.Materialcode)
                    .OrderBy(n=>n.CreatedTime)
                    .OrderByDescending(n => n.StockNumber)
                    .ToListAsync();
                List<FjStock> FjStockList = new List<FjStock>();
                //优先从库位为空的库存进行分拣
                var fjstockModel = wmsMaterialStocks.Where(p => p.PlaceCode == "N/A").ToList();
                if (fjstockModel != null)
                {
                    foreach (var a in fjstockModel)
                    {
                        var FjStockModal = a.Adapt<FjStock>();
                        FjStockModal.FjQty = a.StockNumber;
                        if (item.DistributeQty + a.StockNumber > item.Qty)
                        {
                            FjStockModal.FjQty = item.Qty - item.DistributeQty;
                            item.DistributeQty = item.Qty;
                            FjStockList.Add(FjStockModal);
                            break;
                        }
                        else
                        {
                            item.DistributeQty += a.StockNumber;
                        };
                        FjStockList.Add(FjStockModal);
                    }
                }
                if (item.DistributeQty < item.Qty)
                {
                    foreach (var b in wmsMaterialStocks.Where(x=>x.PlaceCode!="N/A"))
                    {
                        var FjStockModal = b.Adapt<FjStock>();
                        FjStockModal.FjQty = b.StockNumber;
                        if (item.DistributeQty + b.StockNumber > item.Qty)
                        {
                            FjStockModal.FjQty = item.Qty - item.DistributeQty;
                            item.DistributeQty = item.Qty;
                            FjStockList.Add(FjStockModal);
                            break;
                        }
                        else
                        {
                            item.DistributeQty += b.StockNumber;
                        };
                        FjStockList.Add(FjStockModal);
                    }
                }
                
                if (item.DistributeQty< item.Qty) throw Oops.Oh(item.Materialname+"库存数量不足!");
                //循环需要出库的库存生成任务和分拣单
                foreach (var stock in FjStockList)
                {
                    //获取库位信息
                    var wmsPlacModal = await _wmsPlaceRep.FirstOrDefaultAsync(x => x.PlaceCode == stock.PlaceCode);
                    //物料和容器的关系
                    var fjcvmModelList = await _wmsMaterialContainerRep.Where(z =>
                      z.ContainerCode == stock.ContainerCode && z.BindStatus == CommonStatus.ENABLE).ToListAsync();
                    if (wmsPlacModal!=null)
                    {
                        //任务
                        var takmodel = new WmsTask()
                        {
                            TaskNo = Yitter.IdGenerator.YitIdHelper.NextId().ToString(),
                            TaskModel = TaskModel.QUANZIDONG,
                            TaskType = TaskType.CHUKU,
                            TaskLevel = 1,
                            TaskStatus = TaskStatusEnum.WEIZHIXING,
                            OrderNo = fjcvmModelList.FirstOrDefault().OrderNo,
                            OrderDetailsId = item.Id,
                            ContainerCode = stock.ContainerCode,
                            SourcePlace = stock.PlaceCode,
                            ToPlace = wmsPlacModal.Aisle.ToString(), //目标位
                            AreaName = "绝缘立库",
                            IsRead = true, //WCS是否可以读取
                            SendTimes = 1, //发送次数
                            Aisle = wmsPlacModal.Aisle,
                            TaskDodeviceStatus = TaskDodeviceStatusEnum.W,
                            Description = "物料"
                        };
                        await _wmsTaskRep.InsertAsync(takmodel);
                    }
                    // 新增分拣
                    var wmsSortOrder = new WmsSortOrder()
                    {
                        OrderNo = wmsTakeMaterialOrder.NO,
                        Materialcode = stock.MaterialNo,
                        Materialname = stock.MaterialName,
                        OrderDetailID = item.Id,
                        ContainerOrderNo = fjcvmModelList.FirstOrDefault().OrderNo,
                        ProjectCode = item.ProjectCode,
                        TACode = item.TACode,
                        PartCode = item.PartCode,
                        PlaceCode = item.PlaceCode,
                        ContainerCode = stock.ContainerCode,    
                        SortQuantity = stock.FjQty,
                        ActualQuantity = new decimal(0.00),
                        SortStatus = SortStatusEnum.WEIFENJIAN
                    };
                    await _wmsSortOrderRep.InsertNowAsync(wmsSortOrder);
                }
            }
            
        }

        /// <summary>
        /// 删除领料单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsTakeMaterialOrderInput input)
        {
            var wmsTakeMaterialOrder = await _wmsTakeMaterialOrderRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsTakeMaterialOrderRep.DeleteAsync(wmsTakeMaterialOrder);
        }

        /// <summary>
        /// 更新领料单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsTakeMaterialOrderInput input)
        {
            var isExist = await _wmsTakeMaterialOrderRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsTakeMaterialOrder = input.Adapt<WmsTakeMaterialOrder>();
            await _wmsTakeMaterialOrderRep.UpdateAsync(wmsTakeMaterialOrder,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取领料单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsTakeMaterialOrderOutput> Get([FromQuery] QueryeWmsTakeMaterialOrderInput input)
        {
            return (await _wmsTakeMaterialOrderRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsTakeMaterialOrderOutput>();
        }

        /// <summary>
        /// 获取领料单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsTakeMaterialOrderOutput>> List([FromQuery] WmsTakeMaterialOrderInput input)
        {
            return await _wmsTakeMaterialOrderRep.DetachedEntities.ProjectToType<WmsTakeMaterialOrderOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入领料单功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsTakeMaterialOrder", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsTakeMaterialOrderOutput> wmsTakeMaterialOrderList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsTakeMaterialOrderOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsTakeMaterialOrderList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsTakeMaterialOrder>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsTakeMaterialOrder, WmsTakeMaterialOrderOutput>(selectKeys);
            List<WmsTakeMaterialOrder> updates = new();
            List<WmsTakeMaterialOrder> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsTakeMaterialOrderExistSubList = _wmsTakeMaterialOrderRep.Where(filter).Select(selector).ToList();
                    wmsTakeMaterialOrderExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var wmsTakeMaterialOrder in wmsTakeMaterialOrderList) 
                {
                    if (wmsTakeMaterialOrder.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsTakeMaterialOrder.Adapt<WmsTakeMaterialOrder>());
                    }
                    else 
                    {
                        adds.Add(wmsTakeMaterialOrder.Adapt<WmsTakeMaterialOrder>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsTakeMaterialOrderRep.Update(x));
                

                var maxId = _wmsTakeMaterialOrderRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<WmsTakeMaterialOrder>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载领料单的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsTakeMaterialOrder", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据领料单查询参数导出Excel
        /// </summary>
        /// <param name="input">领料单查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsTakeMaterialOrderSearchNonPage input)
        {
            var wmsTakeMaterialOrderList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsTakeMaterialOrderList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsTakeMaterialOrder", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
